package com.ocom.wxapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.dto.Department;
import com.ocom.common.entity.access.EntityMjGroupPer;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.wx.UserAccessPageSetAccessRequest;
import com.ocom.common.request.wx.UserPageAddUserRequest;
import com.ocom.common.request.wx.UserPageOnShowRequest;
import com.ocom.common.request.wx.UserPageUserListRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.response.wx.UserPageOnShowResponse;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.common.vo.AreaInfoVo;
import com.ocom.common.vo.DeptVo;
import com.ocom.common.vo.PersonVo;
import com.ocom.security.authentication.YoCiUser;
import com.ocom.security.utils.SecurityUtils;
import com.ocom.wxapi.client.AccessClientService;
import com.ocom.wxapi.client.HumanClientService;
import com.ocom.wxapi.client.MinioClientService;
import com.ocom.wxapi.service.UserPageService;
import com.ocom.wxapi.vo.userpage.PullFYInfoVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@PreAuthorize("hasRole('ROLE_WX')")
@RequestMapping("/UserPage")
@RestController
public class UserPageController {
    private final Logger log = LoggerFactory.getLogger(UserPageController.class);
    @Autowired
    MinioClientService minioClientService;

    @Autowired
    private UserPageService userPageService;

    @Autowired
    HumanClientService humanClientService;

    @Autowired
    AccessClientService accessClientService;

    @PostMapping("/onShow")
    public Result onShow(@Valid UserPageOnShowRequest request) {


        UserPageOnShowResponse userPageOnShowResponse = new UserPageOnShowResponse();
        Map<String, String> pageFormat = new HashMap<>();
        pageFormat.put("pageTitle", "用户管理+");
        pageFormat.put("lblDeptCaption", "子部门");
        pageFormat.put("cmdDeptCaption", "+添加子部门");
        pageFormat.put("lblUserCaption", "成员");
        pageFormat.put("cmdUserCaption", "+添加成员");
        userPageOnShowResponse.setPageFormat(pageFormat);


        Result result = humanClientService.GetDeptInfo(request.getCompanyId(), request.getDeptId(), null);

        if (result.getCode() == 200) {

            List<EntityDeptInfo> list = JSON.parseObject(JSON.toJSONString(result.getData()), List.class);

            if (list != null && list.size() > 0) {
                ArrayList<DeptVo> deptList = new ArrayList<>();
                for (Object object : list) {
                    EntityDeptInfo entityDeptInfo = JSON.parseObject(JSON.toJSONString(object), EntityDeptInfo.class);
                    DeptVo deptVo = new DeptVo();
                    deptVo.setDeptId(entityDeptInfo.getDeptId());
                    deptVo.setDeptName(entityDeptInfo.getDeptName());
                    deptVo.setGrade(entityDeptInfo.getGrade());
                    deptVo.setParentDeptId(entityDeptInfo.getParentDeptId());
                    deptList.add(deptVo);
                }
                userPageOnShowResponse.setDeptList(deptList);
            }
        }

        return ResultUtil.success(userPageOnShowResponse);
    }

    //2.10.3 显示用户列表（UserPage/userList）
    @PostMapping("/userList")
    public Result userList(@Valid UserPageUserListRequest request) {
        if (StringUtils.isNull(request.getCompanyId())) {
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "单位编号为空");
        }
//        if (StringUtils.isNull(request.getPId())) {
//            log.error("人员编号为空");
//            return ResultUtil.error(ResultEnum.Err_203, "人员编号为空");
//        }
        if (StringUtils.isNull(request.getDeptId())) {
            log.error("部门编号");
            return ResultUtil.error(ResultEnum.Err_203, "部门编号为空");
        }
        return userPageService.userList(request);
    }


    @PostMapping("/addUser")
    public Result addUser(@Valid UserPageAddUserRequest request) {

        PersonVo personVo = new PersonVo();

        personVo.setComId(request.getCompanyId());
        personVo.setPName(request.getUserName());
        personVo.setPPhone(request.getTelephone());
        personVo.setPIdentity(request.getIdentity());
        personVo.setPCode(request.getPCode());
        personVo.setDeptId(0l);
        personVo.setPId(request.getPId());
        personVo.setPPhotoUrl(request.getPPhotoUrl());
        Result result = humanClientService.AddPerson(personVo);
        if (result.getCode() != 200) {
            log.error("添加人员失败， 参数 【{}】", personVo);
            return ResultUtil.error(result.getCode());
        }
        EntityPersonnelInfo personnelInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
        Result areaList = accessClientService.getAreaList(request.getCompanyId(), personnelInfo.getPId());
        if (result.getCode() != 200) {
            log.error("获取区域列表失败， 参数 【{}】", personVo);
            return ResultUtil.error(areaList.getCode());
        }
        log.info("areaList{{}}",areaList);

        List<AreaInfoVo> areaInfoVos = JSONObject.parseArray(JSON.toJSONString(areaList.getData()), AreaInfoVo.class);

        log.info("areaInfoVos{{}}",areaInfoVos);

        for (AreaInfoVo areaInfoVo : areaInfoVos) {
            UserAccessPageSetAccessRequest userAccessPageSetAccessRequest = new UserAccessPageSetAccessRequest();
            userAccessPageSetAccessRequest.setRegionId(0L);
            userAccessPageSetAccessRequest.setCompanyId(request.getCompanyId());
            userAccessPageSetAccessRequest.setUserId(personnelInfo.getPId());
            userAccessPageSetAccessRequest.setAreaNo(areaInfoVo.getAreaNo());
            userAccessPageSetAccessRequest.setRoleI(2L);
            userAccessPageSetAccessRequest.setPId(request.getPId());
            Result result1 = accessClientService.setAccess(userAccessPageSetAccessRequest);
            if (result1.getCode() == 200) {
                EntityMjGroupPer entityMjGroupPer = JSON.parseObject(JSON.toJSONString(result1.getData()), EntityMjGroupPer.class);
                log.info("entityMjGroupPer{{}}",entityMjGroupPer);
                if (entityMjGroupPer != null) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", entityMjGroupPer.getPId());
                    map.put("role_i", entityMjGroupPer.getGroupNo());
                    log.info("map{{}}",map);
                    return ResultUtil.info(result1.getCode(), result1.getMsg(), map);
                }
            }
        }
        return ResultUtil.info(200, "已成功添加用户：" + request.getUserName());
    }

    /**
     * 拉取防疫信息（UserPage/pullFYInfo ）
     */
    @PostMapping("/pullFYInfo")
    public Result pullFYInfo(@Valid PullFYInfoVo pullFYInfoVo) {
        if (StringUtils.isNull(pullFYInfoVo.getComId())) {
            log.error("单位编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "单位编号为空");
        }
        if (StringUtils.isNull(pullFYInfoVo.getPId())) {
            log.error("人员编号为空");
            return ResultUtil.error(ResultEnum.Err_203, "人员编号为空");
        }
        return userPageService.pullFYInfo(pullFYInfoVo);
    }


    @PostMapping("/deptList")
    public Result onShow(Department request) {
        request.setPage(1);
        request.setSize(200);
//        return humanClientService.departmentGetDeptInfos(request);

        YoCiUser yoCiUser = SecurityUtils.getYoCiUser();

        if(!yoCiUser.getDeptId().equals("0")){
            return humanClientService.getDeptList(yoCiUser.getComId(),Long.valueOf(yoCiUser.getDeptId()),0);
        }else{
            return humanClientService.getDeptList(yoCiUser.getComId(),Long.valueOf(yoCiUser.getDeptId()),1);

        }

    }
}
